--[[

  Copyright 2017 Stefano Mazzucco <stefano AT curso DOT re>

  This program is free software: you can redistribute it and/or modify it under
  the terms of the GNU General Public License as published by the Free Software
  Foundation, either version 3 of the License, or (at your option) any later
  version.

  This program is distributed in the hope that it will be useful, but WITHOUT
  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
  details.

  You should have received a copy of the GNU General Public License along with
  this program.  If not, see <https://www.gnu.org/licenses/gpl-3.0.html>.

]]

--- My personal Awesome Configuration
-- Awesome Version: 4.x

-- Standard awesome library
local awesome = awesome -- luacheck: ignore
local root = root -- luacheck: ignore
local screen = screen -- luacheck: ignore
local client = client -- luacheck: ignore
local instance = instance -- luacheck: ignore
local mouse = mouse -- luacheck: ignore

local gears = require("gears")
local awful = require("awful")
require("awful.autofocus")
-- Widget and layout library
local wibox = require("wibox")
-- Theme handling library
local beautiful = require("beautiful")
local dpi = require("beautiful.xresources").apply_dpi
local gtk_settings = require("lgi").Gtk.Settings.get_default()
-- Notification library
local naughty = require("naughty")
local menubar = require("menubar")
local hotkeys_popup = require("awful.hotkeys_popup").widget

local media_players = require("media_players")


--[[

   gears.cycle_value is not present in awesome 4.3 graft it to make the
   layoutlist example work

   - https://awesomewm.org/doc/api/classes/awful.widget.layoutlist.html
   - https://github.com/awesomeWM/awesome/pull/2942/files
   - https://github.com/awesomeWM/awesome/issues/2869
]]

--- Get the next (or previous) value from a table and cycle if necessary.
--
-- If the table contains the same value multiple type (aka, is not a set), the
-- `first_index` has to be specified.
--
-- @tparam table tbl The input table.
-- @param value A value from the table.
-- @tparam[opt=1] number step_size How many element forward (or backward) to pick.
-- @tparam[opt=nil] function filter An optional function. When it returns
--  `false`, the element are skipped until a match if found. It takes the value
--  as its sole parameter.
-- @tparam[opt=1] number start_at Where to start the lookup from.
-- @return The value. If no element match, then `nil` is returned.
-- @treturn number|nil The element (if any) key.
-- @staticfct gears.table.cycle_value
function cycle_value(tbl, value, step_size, filter, start_at)
    local k = gears.table.hasitem(tbl, value, true, start_at)
    if not k then return end

    step_size = step_size or 1
    local new_key = gears.math.cycle(#tbl, k + step_size)

    if filter and not filter(tbl[new_key]) then
        for i=1, #tbl, step_size do
            local k2 = gears.math.cycle(#tbl, new_key + i)
            if filter(tbl[k2]) then
                return tbl[k2], k2
            end
        end
        return
    end

    return tbl[new_key], new_key
end

gears.table.cycle_value = gears.table.cycle_value or cycle_value


-- Quodlibet
local quodlibet = media_players.quodlibet
-- Vlc
local vlc = media_players.vlc

-- This is used later as the default terminal and editor to run.
local terminal = "terminology"

local Quake = require("quake")
local quake_name = "QuakeTerminal"
local quake_command = terminal .. " -n " .. quake_name
local quake = Quake:new({
    name = quake_name,
    cmd = quake_command,
    client_props = {
      maximized_horizontal = true,
      maximized = false,
    }
})

local function quake_start()
  awful.spawn.easy_async(
    'pgrep -c -f "' .. quake_command .. '"',
    function (stdout, _, _, exitcode)

      if exitcode ~= 0 then
        quake:spawn()
        naughty.notify({title = "Quake Terminal started"})
      end

      local nterminals = tonumber(stdout)
      if nterminals > 1 then
        naughty.notify({
            preset = naughty.config.presets.critical,
            title = "Too Many Quake Terminals",
            text = nterminals .. " terminals have been spawned"
        })
      end
    end
  )
end

local function make_kill(signal, message)

  return function (c)
    local pid = c.pid

    if not pid then return end

    awful.spawn.easy_async(
      "kill " .. signal .. " " ..  pid,
      function (_, stderr, _, exitcode)
        if exitcode ~= 0 then
          naughty.notify({
              title = string.format(
                "%s %s (FAILURE)",
                message,
                c.name
              ),
              text = stderr,
              preset = naughty.config.preset.critical
          })
        else
          naughty.notify({
              title = string.format(
                "%s %s",
                message,
                c.name
              )
          })
        end
    end)
  end

end

local suspend = make_kill("-STOP", "Suspend")
local resume = make_kill("-CONT", "Resume")

local function lock_screen()
  awful.spawn("xset s activate")
end

local function toggle_suspend()
  local c = client.focus
  if c ~=nil then
    local check_state_cmd = string.format("ps -q %s -o state=", c.pid)
    awful.spawn.easy_async(
      check_state_cmd,
      function (stdout, stderr, _, exitcode)
        if exitcode == 0 then
          if stdout:match("^S") then
            suspend(c)
            c.name = "[SUSPENDED] " .. c.name
          elseif stdout:match("^T") then
            resume(c)
            c.name = c.name:gsub("%[SUSPENDED%] ", "")
          end
        else
          naughty.notify({
              title = string.format(
                "Failed to get state information for %s",
                c.name
              ),
              text = stderr,
              preset = naughty.config.presets.critical
          })
        end
    end)
  end
end

naughty.config.defaults.position = "top_middle"

-- {{{ Error handling
-- Check if awesome encountered an error during startup and fell back to
-- another config (This code will only ever execute for the fallback config)
if awesome.startup_errors then
  naughty.notify({ preset = naughty.config.presets.critical,
                   title = "Oops, there were errors during startup!",
                   text = awesome.startup_errors })
end

-- Handle runtime errors after startup
do
  local in_error = false
  awesome.connect_signal("debug::error", function (err)
                           -- Make sure we don't go into an endless error loop
                           if in_error then return end
                           in_error = true

                           naughty.notify({ preset = naughty.config.presets.critical,
                                            title = "Oops, an error happened!",
                                            text = tostring(err) })
                           in_error = false
  end)
end
-- }}}

-- {{{ Variable definitions
-- Themes define colours, icons, font and wallpapers.
local theme = dofile(gears.filesystem.get_themes_dir() .. "gtk/theme.lua")

theme.icon_theme = gtk_settings.gtk_icon_theme_name
theme.font = gtk_settings.gtk_font_name

-- https://awesomewm.org/recipes/awesome-taglist/
theme.taglist_font = "awesomewm-font 13"

theme.useless_gap   = dpi(0)

beautiful.init(theme)

beautiful.notification_icon_size = 64

quake_start()

-- require *after* `beautiful.init` or the theme will be inconsistent!
local capslock = require("external.capslock.capslock")

local pulse = require("pulseaudio_widget")
local connman = require("connman_widget")
local power = require("power_widget")
power.critical_percentage = 9
power.warning_config = {
  percentage = 21,
  preset = {
    shape = gears.shape.rounded_rect,
    bg = "#FFFF00",
    fg = "#000000",
    timeout = 3,
  },
  message = "The battery is getting low",
}
local calendar = require("external.calendar")

-- Default modkey.
-- Usually, Mod4 is the key with a logo between Control and Alt.
-- If you do not like this or do not have such a key,
-- I suggest you to remap Mod4 to another key using xmodmap or other tools.
-- However, you can use another modifier like Mod1, but it may interact with others.
local modkey = "Mod4"

do
   -- https://awesomewm.org/doc/api/classes/awful.widget.layoutlist.html
   awful.layout.layouts = {
      -- Table of layouts to cover with awful.layout.inc, order matters.
      awful.layout.suit.spiral.dwindle,
      awful.layout.suit.tile,
      awful.layout.suit.tile.left,
      awful.layout.suit.tile.bottom,
      awful.layout.suit.tile.top,
      awful.layout.suit.fair,
      awful.layout.suit.fair.horizontal,
      awful.layout.suit.floating,
      awful.layout.suit.spiral,
      awful.layout.suit.max,
      awful.layout.suit.max.fullscreen,
      awful.layout.suit.magnifier
   }

   local layout_list = awful.widget.layoutlist {
      base_layout = wibox.widget {
         spacing         = 5,
         forced_num_cols = 5,
         layout          = wibox.layout.grid.vertical,
      },
      widget_template = {
         {
            {
               id            = 'icon_role',
               forced_height = 22,
               forced_width  = 22,
               widget        = wibox.widget.imagebox,
            },
            margins = 4,
            widget  = wibox.container.margin,
         },
         id              = 'background_role',
         forced_width    = 24,
         forced_height   = 24,
         shape           = gears.shape.rounded_rect,
         widget          = wibox.container.background,
      },
   }


   local layout_popup = awful.popup {
      widget = wibox.widget {
         layout_list,
         margins = 4,
         widget  = wibox.container.margin,
      },
      border_color = beautiful.border_color,
      border_width = beautiful.border_width,
      placement    = awful.placement.centered,
      ontop        = true,
      visible      = false,
      shape        = gears.shape.rounded_rect
   }

   awful.keygrabber { -- https://awesomewm.org/doc/api/classes/awful.keygrabber.html
      start_callback = function() layout_popup.visible = true end,
      stop_callback  = function()
         layout_popup.visible = false
         layout_popup._do_cycle = false  -- custom attribute to signal whether to cycle layouts
      end,
      export_keybindings = true,
      release_event = "release",
      stop_key = {"Escape", "Super_L", "Super_R", "Return"},
      keybindings = {
         {
            {modkey}, " " ,
            function()
               if not layout_popup._do_cycle then
                  layout_popup._do_cycle = true
               else
                  awful.layout.set(gears.table.cycle_value(layout_list.layouts, layout_list.current_layout, 1), nil)
               end
            end
         },
         {
            {modkey, "Shift"} , " " ,
            function()
               if not layout_popup._do_cycle then
                  layout_popup._do_cycle = true
               else
                  awful.layout.set(gears.table.cycle_value(layout_list.layouts, layout_list.current_layout, -1), nil)
               end
            end
         },
      }
   }
end

-- {{{ Helper functions
local function client_menu_toggle_fn()
  local inst = nil

  return function ()
    if inst and inst.wibox.visible then
      inst:hide()
      inst = nil
    else
      inst = awful.menu.clients({ theme = { width = 250 } })
    end
  end
end
-- }}}

-- {{{ Menu

-- Menubar configuration
menubar.utils.terminal = terminal -- Set the terminal for applications that require it
-- }}}

-- {{{ Wibar
-- Create a textclock widget
local mytextclock = wibox.widget.textclock()
calendar:register(mytextclock)

-- Create a wibox for each screen and add it
local taglist_buttons = awful.util.table.join(
  awful.button({ }, 1, function(t) t:view_only() end),
  awful.button({ modkey }, 1, function(t)
      if client.focus then
        client.focus:move_to_tag(t)
      end
  end),
  awful.button({ }, 3, awful.tag.viewtoggle),
  awful.button({ modkey }, 3, function(t)
      if client.focus then
        client.focus:toggle_tag(t)
      end
  end),
  awful.button({ }, 4, function(t) awful.tag.viewnext(t.screen) end),
  awful.button({ }, 5, function(t) awful.tag.viewprev(t.screen) end)
)

local tasklist_buttons = awful.util.table.join(
  awful.button({ }, 1, function (c)
      if c == client.focus then
        c.minimized = true
      else
        -- Without this, the following
        -- :isvisible() makes no sense
        c.minimized = false
        if not c:isvisible() and c.first_tag then
          c.first_tag:view_only()
        end
        -- This will also un-minimize
        -- the client, if needed
        client.focus = c
        c:raise()
      end
  end),
  awful.button({ }, 3, client_menu_toggle_fn()),
  awful.button({ }, 4, function ()
      awful.client.focus.byidx(1)
  end),
  awful.button({ }, 5, function ()
      awful.client.focus.byidx(-1)
end))

local function set_wallpaper(s)
  -- Wallpaper
  if beautiful.wallpaper then
    local wallpaper = beautiful.wallpaper
    -- If wallpaper is a function, call it with the screen
    if type(wallpaper) == "function" then
      wallpaper = wallpaper(s)
    end
    gears.wallpaper.maximized(wallpaper, s, true)
  end
end

-- Re-set wallpaper when a screen's geometry changes (e.g. different resolution)
screen.connect_signal("property::geometry", set_wallpaper)

local my_tags = { "A", "W", "E", "S", "O", "M", "E" }

awful.screen.connect_for_each_screen(function(s)
    -- Wallpaper
    set_wallpaper(s)

    -- Each screen has its own tag table.
    -- https://awesomewm.org/recipes/awesome-taglist/
    awful.tag(my_tags, s, awful.layout.layouts[1])

    -- Create a promptbox for each screen
    s.mypromptbox = awful.widget.prompt()
    -- Create an imagebox widget which will contains an icon indicating which layout we're using.
    -- We need one layoutbox per screen.
    s.mylayoutbox = awful.widget.layoutbox(s)
    s.mylayoutbox:buttons(awful.util.table.join(
                            awful.button({ }, 1, function () awful.layout.inc( 1) end),
                            awful.button({ }, 3, function () awful.layout.inc(-1) end),
                            awful.button({ }, 4, function () awful.layout.inc( 1) end),
                            awful.button({ }, 5, function () awful.layout.inc(-1) end)))
    -- Create a taglist widget
    s.mytaglist = awful.widget.taglist({
        screen = s,
        filter = awful.widget.taglist.filter.all,
        buttons = taglist_buttons
    })
    -- and apply shape to it (needed by gtk theme)
    if beautiful.taglist_shape_container then
        local background_shape_wrapper = wibox.container.background(s.mytaglist)
        background_shape_wrapper._do_taglist_update_now = s.mytaglist._do_taglist_update_now
        background_shape_wrapper._do_taglist_update = s.mytaglist._do_taglist_update
        background_shape_wrapper.shape = beautiful.taglist_shape_container
        background_shape_wrapper.shape_clip = beautiful.taglist_shape_clip_container
        background_shape_wrapper.shape_border_width = beautiful.taglist_shape_border_width_container
        background_shape_wrapper.shape_border_color = beautiful.taglist_shape_border_color_container
        s.mytaglist = background_shape_wrapper
    end

    -- Create a tasklist widget
    s.mytasklist = awful.widget.tasklist({
      screen = s,
      filter = awful.widget.tasklist.filter.currenttags,
      buttons = tasklist_buttons,
      widget_template = beautiful.tasklist_widget_template
    })

    -- Create the wibox
    s.mywibox = awful.wibar({ position = "top", screen = s })

    -- Add widgets to the wibox
    s.mywibox:setup {
      layout = wibox.layout.align.horizontal,
      { -- Left widgets
        layout = wibox.layout.fixed.horizontal,
        s.mytaglist,
        s.mypromptbox,
      },
      s.mytasklist, -- Middle widget
      { -- Right widgets
        layout = wibox.layout.fixed.horizontal,
        wibox.widget.systray(),
        capslock,
        connman,
        power,
        mytextclock,
        pulse,
        s.mylayoutbox,
      },
    }
end)
-- }}}

-- {{{ Mouse bindings
root.buttons(awful.util.table.join(
               awful.button({ }, 4, awful.tag.viewnext),
               awful.button({ }, 5, awful.tag.viewprev)
))
-- }}}

-- {{{ Key bindings
local globalkeys = awful.util.table.join(
  awful.key({ modkey,           }, "s",      hotkeys_popup.show_help,
    {description="show help", group="awesome"}),
  awful.key({ modkey,           }, "Left",   awful.tag.viewprev,
    {description = "view previous", group = "tag"}),
  awful.key({ modkey,           }, "Right",  awful.tag.viewnext,
    {description = "view next", group = "tag"}),
  awful.key({ modkey,           }, "Escape", awful.tag.history.restore,
    {description = "go back", group = "tag"}),

  capslock.key,

  awful.key({ modkey,           }, "j",
    function ()
      awful.client.focus.byidx( 1)
    end,
    {description = "focus next by index", group = "client"}
  ),
  awful.key({ modkey,           }, "k",
    function ()
      awful.client.focus.byidx(-1)
    end,
    {description = "focus previous by index", group = "client"}
  ),

  -- Layout manipulation
  awful.key({ modkey, "Shift"   }, "j", function () awful.client.swap.byidx(  1)    end,
    {description = "swap with next client by index", group = "client"}),
  awful.key({ modkey, "Shift"   }, "k", function () awful.client.swap.byidx( -1)    end,
    {description = "swap with previous client by index", group = "client"}),
  awful.key({ modkey, "Control" }, "j", function () awful.screen.focus_relative( 1) end,
    {description = "focus the next screen", group = "screen"}),
  awful.key({ modkey, "Control" }, "k", function () awful.screen.focus_relative(-1) end,
    {description = "focus the previous screen", group = "screen"}),
  awful.key({ modkey,           }, "u", awful.client.urgent.jumpto,
    {description = "jump to urgent client", group = "client"}),
  awful.key({ modkey,           }, "Tab",
    function ()
      awful.spawn("rofi -show window")
    end,
    {description = "select windows", group = "client"}),


  -- Standard program
  awful.key({ modkey,           }, "KP_Enter", function () awful.spawn(terminal) end,
    {description = "open a terminal", group = "launcher"}),
  awful.key({ modkey,           }, "Return", function () awful.spawn(terminal) end,
    {description = "open a terminal", group = "launcher"}),
  awful.key({ modkey, "Control" }, "r", awesome.restart,
    {description = "reload awesome", group = "awesome"}),
  awful.key({ modkey, "Shift"   }, "q",
    function ()
      naughty.notify(
        {title = "About to quit Awesome!",
         position = "top_left",
         timeout = 5,
         preset = naughty.config.presets.critical})
      awful.prompt.run(
        {prompt = "QUIT AWESOME [Y/N]? ",
         textbox = awful.screen.focused().mypromptbox.widget,
         exe_callback =   function (arg)
           if arg:lower() == "y" then
             awesome.quit()
           end
         end
        }
      )
    end,
    {description = "quit awesome", group = "awesome"}),

  awful.key({ modkey,           }, "l",     function () awful.tag.incmwfact( 0.05)          end,
    {description = "increase master width factor", group = "layout"}),
  awful.key({ modkey,           }, "h",     function () awful.tag.incmwfact(-0.05)          end,
    {description = "decrease master width factor", group = "layout"}),
  awful.key({ modkey, "Shift"   }, "h",     function () awful.tag.incnmaster( 1, nil, true) end,
    {description = "increase the number of master clients", group = "layout"}),
  awful.key({ modkey, "Shift"   }, "l",     function () awful.tag.incnmaster(-1, nil, true) end,
    {description = "decrease the number of master clients", group = "layout"}),
  awful.key({ modkey, "Control" }, "h",     function () awful.tag.incncol( 1, nil, true)    end,
    {description = "increase the number of columns", group = "layout"}),
  awful.key({ modkey, "Control" }, "l",     function () awful.tag.incncol(-1, nil, true)    end,
    {description = "decrease the number of columns", group = "layout"}),

  awful.key({ modkey, "Control" }, "n",
    function ()
      local c = awful.client.restore()
      -- Focus restored client
      if c then
        client.focus = c
        c:raise()
      end
    end,
    {description = "restore minimized", group = "client"}),

  -- Prompt
  awful.key({ modkey },            "r",     function () awful.screen.focused().mypromptbox:run() end,
    {description = "run prompt", group = "launcher"}),

  awful.key({ modkey }, "x",
    function ()
      awful.prompt.run {
        prompt       = "Run Lua code: ",
        textbox      = awful.screen.focused().mypromptbox.widget,
        exe_callback = awful.util.eval,
        history_path = awful.util.get_cache_dir() .. "/history_eval"
      }
    end,
    {description = "lua execute prompt", group = "awesome"}),

  -- Menubar
  awful.key({ modkey }, "p", function() awful.spawn("rofi -show drun") end,
    {description = "show the application menu", group = "launcher"}),

  -- Pulseaudio
  awful.key({ }, "XF86AudioRaiseVolume", pulse.volume_up),
  awful.key({ }, "XF86AudioLowerVolume", pulse.volume_down),
  awful.key({ }, "XF86AudioMute",  pulse.toggle_muted),
  awful.key({"Shift"}, "XF86AudioRaiseVolume", pulse.volume_up_mic),
  awful.key({"Shift"}, "XF86AudioLowerVolume", pulse.volume_down_mic),
  awful.key({"Shift"}, "XF86AudioMute",  pulse.toggle_muted_mic),
  awful.key({ }, "XF86AudioMicMute",  pulse.toggle_muted_mic),

  -- QuodLibet music player
  awful.key({}, "XF86AudioPlay", quodlibet.play_pause),
  awful.key({}, "XF86AudioStop", quodlibet.stop),
  awful.key({"Control"}, "XF86AudioStop", quodlibet.quit),
  awful.key({}, "XF86AudioPrev", quodlibet.previous),
  awful.key({}, "XF86AudioNext", quodlibet.next),
  awful.key({modkey}, "i", quodlibet.notify),

  -- Vlc media player
  awful.key({"Shift"}, "XF86AudioPlay", vlc.play_pause),
  awful.key({"Shift"}, "XF86AudioStop", vlc.stop),
  awful.key({"Shift", "Control"}, "XF86AudioStop", vlc.quit),
  awful.key({"Shift"}, "XF86AudioPrev", vlc.previous),
  awful.key({"Shift"}, "XF86AudioNext", vlc.next),
  awful.key({modkey, "Shift"}, "i", vlc.notify),

  -- Xscreensaver: Ctrl+alt+l
  awful.key({"Control", "Mod1"}, "l", lock_screen,
    {description = "lock the screen", group = "screen"}),
  awful.key({}, "XF86ScreenSaver", lock_screen,
    {description = "lock the screen", group = "screen"}),

  -- Quake Terminal
  awful.key(
    {},
    "F12",
    function ()
      quake:spawn()
    end,
    {
      description = "toggle the drop-down terminal",
      group = "launcher"
    }
  )
)

local clientkeys = awful.util.table.join(
  awful.key({ modkey,           }, "f",
    function (c)
      c.fullscreen = not c.fullscreen
      c:raise()
    end,
    {description = "toggle fullscreen", group = "client"}),
  awful.key({ modkey, "Shift"   }, "c",      function (c) c:kill()                         end,
    {description = "close", group = "client"}),
  awful.key({ modkey, "Control" }, "space",  awful.client.floating.toggle                     ,
    {description = "toggle floating", group = "client"}),
  awful.key({ modkey, "Control" }, "KP_Enter", function (c) c:swap(awful.client.getmaster()) end,
    {description = "move to master", group = "client"}),
  awful.key({ modkey, "Control" }, "Return", function (c) c:swap(awful.client.getmaster()) end,
    {description = "move to master", group = "client"}),
  awful.key({ modkey,           }, "o",      function (c) c:move_to_screen()               end,
    {description = "move to screen", group = "client"}),
  awful.key({ modkey,           }, "t",      function (c) c.ontop = not c.ontop            end,
    {description = "toggle keep on top", group = "client"}),
  awful.key({ modkey,           }, "n",
    function (c)
      -- The client currently has the input focus, so it cannot be
      -- minimized, since minimized clients can't have the focus.
      c.minimized = true
    end ,
    {description = "minimize", group = "client"}),
  awful.key({ modkey,           }, "m",
    function (c)
      c.maximized = not c.maximized
      c:raise()
    end ,
    {description = "maximize", group = "client"}),

  awful.key({ modkey, }, "q", toggle_suspend,
    { description = "toggle suspend", group = "client" })
)

-- Bind all key numbers to tags.
-- Be careful: we use keycodes to make it works on any keyboard layout.
-- This should map on the top row of your keyboard.
for i in ipairs(my_tags) do
  globalkeys = awful.util.table.join(globalkeys,
                                     -- View tag only.
                                     awful.key({ modkey }, "#" .. i + 9,
                                       function ()
                                         local scr = awful.screen.focused()
                                         local tag = scr.tags[i]
                                         if tag then
                                           tag:view_only()
                                         end
                                       end,
                                       {description = "view tag #"..i, group = "tag"}),
                                     -- Toggle tag display.
                                     awful.key({ modkey, "Control" }, "#" .. i + 9,
                                       function ()
                                         local scr = awful.screen.focused()
                                         local tag = scr.tags[i]
                                         if tag then
                                           awful.tag.viewtoggle(tag)
                                         end
                                       end,
                                       {description = "toggle tag #" .. i, group = "tag"}),
                                     -- Move client to tag.
                                     awful.key({ modkey, "Shift" }, "#" .. i + 9,
                                       function ()
                                         if client.focus then
                                           local tag = client.focus.screen.tags[i]
                                           if tag then
                                             client.focus:move_to_tag(tag)
                                           end
                                         end
                                       end,
                                       {description = "move focused client to tag #"..i, group = "tag"}),
                                     -- Toggle tag on focused client.
                                     awful.key({ modkey, "Control", "Shift" }, "#" .. i + 9,
                                       function ()
                                         if client.focus then
                                           local tag = client.focus.screen.tags[i]
                                           if tag then
                                             client.focus:toggle_tag(tag)
                                           end
                                         end
                                       end,
                                       {description = "toggle focused client on tag #" .. i, group = "tag"})
  )
end

local clientbuttons = awful.util.table.join(
  awful.button({ }, 1, function (c) client.focus = c; c:raise() end),
  awful.button({ modkey }, 1, awful.mouse.client.move),
  awful.button({ modkey }, 3, awful.mouse.client.resize))

-- Set keys
root.keys(globalkeys)
-- }}}

-- {{{ Rules
-- Rules to apply to new clients (through the "manage" signal).
awful.rules.rules = {
  -- All clients will match this rule.
  { rule = { },
    properties = { border_width = beautiful.border_width,
                   border_color = beautiful.border_normal,
                   focus = awful.client.focus.filter,
                   raise = true,
                   keys = clientkeys,
                   buttons = clientbuttons,
                   screen = awful.screen.preferred,
                   placement = awful.placement.no_overlap + awful.placement.no_offscreen
    }
  },

  -- Floating clients.
  { rule_any = {
      instance = {
        "DTA",  -- Firefox addon DownThemAll.
        "copyq",  -- Includes session name in class.
        "pinentry",
      },
      class = {
        "1Password",
        "Arandr",
        "Gpick",
        "Kruler",
        "MessageWin",  -- kalarm.
        "Sxiv",
        "Tor Browser", -- Needs a fixed window size to avoid fingerprinting by screen size.
        "Wpa_gui",
        "pinentry",
        "veromix",
        "xtightvncviewer",
        "MPlayer",
        "Vlc",
        "Pidgin",
        "Quodlibet",
	"Pinentry",
        "qemu-system-x86_64",
      },
      name = {
        "Event Tester",  -- xev.
        "Task Manager - Chromium",
      },
      role = {
        "AlarmWindow",  -- Thunderbird's calendar.
        "ConfigManager",  -- Thunderbird's about:config.
        "pop-up",       -- e.g. Google Chrome's (detached) Developer Tools.
        "About",        -- e.g. "About Firefox"
        "page-info", -- Firefox page information.
      }
  }, properties = { floating = true }},

  -- Do not add titlebars to normal clients and dialogs
  { rule_any = {type = { "normal", "dialog" }
               }, properties = { titlebars_enabled = false }
  },

}
-- }}}

-- {{{ Signals
-- Signal function to execute when a new client appears.
client.connect_signal("manage", function (c)
                        -- Set the windows at the slave,
                        -- i.e. put it at the end of others instead of setting it master.
                        -- if not awesome.startup then awful.client.setslave(c) end

                        if awesome.startup and
                          not c.size_hints.user_position
                        and not c.size_hints.program_position then
                          -- Prevent clients from being unreachable after screen count changes.
                          awful.placement.no_offscreen(c)
                        end
end)

-- Enable sloppy focus, so that focus follows mouse.
client.connect_signal("mouse::enter", function(c)
    c:emit_signal("request::activate", "mouse_enter", {raise = false})
end)

client.connect_signal("focus", function(c) c.border_color = beautiful.border_focus end)
client.connect_signal("unfocus", function(c) c.border_color = beautiful.border_normal end)
-- }}}
